package com.hspedu.homework;

/**
 * @Author Stringzhua
 * @Date 2024/3/15 18:23
 * description:
 */
public class homework02_daan {
    public static void main(String[] args) {
        T t = new T();
        Thread thread1 = new Thread(t);
        thread1.setName("t1");
        Thread thread2 = new Thread(t);
        thread1.setName("t2");
        thread1.start();
        thread2.start();
    }
}

//取款线程
//涉及多个线程共享资源,所以使用Runnable方式
class T implements Runnable {
    private double money = 10000;


    @Override
    public synchronized void run() {
        while (true) {
            //1.使用synchronized实现线程同步
            //2.当多个线程执行到这里时,就会去争夺this对象锁
            //this对象锁是非公平锁
            //3.哪个线程获取(争夺)到this对象就执行synchronized代码块
            //4.争夺不到this对象锁的就会blocked,准备下次争夺
            synchronized (this) {
                //先判断余额是否足够
                if (money < 1000) {
                    System.out.println("余额不足");
                    break;
                }

                money -= 1000;
                System.out.println(Thread.currentThread().getName() + " 取出了1000 当前余额=" + money);
            }
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
}
